package com.zhouyangyang.shangcheng.file.controller;

import com.zhouyangyang.entity.Result;
import com.zhouyangyang.entity.StatusCode;
import com.zhouyangyang.file.pojo.FastDFSFile;
import com.zhouyangyang.shangcheng.file.client.FastDFSClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @PackageName: com.zhouyangyang.shangcheng.file.controller
 * @ClassName: FileController
 * @Author: zhouyangyang
 * @Date: 2020/7/26 15:44
 * @Description:
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file){
        try {
            if (file.isEmpty()){
                throw new RuntimeException("文件不存在");
            }
            //获取文件的完整名
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)){
                throw new RuntimeException("文件不存在");
            }
            //获取文件的扩展名称:.jpg
            String extension = FilenameUtils.getExtension(originalFilename);
            //获取文件内容
            byte[] bytes = file.getBytes();
            //获取文件上传的封装实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,bytes,extension);
            //基于工具类进行文件上传,并接受返回参数  String[]
            String[] upload = FastDFSClient.upload(fastDFSFile);
            //封装返回结果
            String url = FastDFSClient.getTrackerUrl()+upload[0]+upload[1];
            return new Result(true, StatusCode.OK,"上传成功",url);
        } catch (IOException e) {
            return new Result(false, StatusCode.ERROR,"文件上传失败");
        }
    }
}
